package tl_client

import (
	"crypto/md5"
	"encoding/hex"
	"log"
	"os"
	"syscall"

	"github.com/ncw/directio"
)

func DioWrtieFile(abs_file_path string, content string) {
	h := md5.New()
	h.Write([]byte(content))

	res := hex.EncodeToString(h.Sum(nil))
	log.Printf("hash md5Bytes: %v", res)

	block := directio.AlignedBlock(directio.BlockSize)
	copy(block, res)

	fileMode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
	if GlbClientArgs.IsDsync {
		fileMode = fileMode | syscall.O_DSYNC
	}

	if GlbClientArgs.IsFsync {
		fileMode = fileMode | syscall.O_FSYNC
	}

	file, err := directio.OpenFile(abs_file_path, fileMode, 0o777)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	n, err := file.Write(block)
	if err != nil {
		panic(err)
	}
	if n != len(block) {
		panic("write file error")
	}

	err = file.Sync()
	if err != nil {
		log.Printf("file sync error")
		panic(err)
	}

	log.Printf("write file success, file , mode, content: %v, %v, %v", abs_file_path, fileMode, content)
	// 进行文件操作
}

func WrtieFile(abs_file_path string, content string) {
	fileMode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
	if GlbClientArgs.IsDsync {
		fileMode = fileMode | syscall.O_DSYNC
	}

	if GlbClientArgs.IsFsync {
		fileMode = fileMode | syscall.O_FSYNC
	}

	file, err := os.OpenFile(abs_file_path, fileMode, 0o777)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	n, err := file.Write([]byte(content))
	if err != nil {
		panic(err)
	}
	if n != len(content) {
		panic("write file error")
	}
	log.Printf("write file success, file , mode, content: %v, %v, %v", abs_file_path, fileMode, content)
}
